package com.ljs.threadpooldemo.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@Slf4j
public class CorsConfig implements WebMvcConfigurer {
    @Value("${file.linuxPath}")
    String linuxPath;
    @Value("${file.winPath}")
    String winPath;
    /**
     * 指定自定义解析器
     * 将 multipartResolver 指向我们刚刚创建好的继承 CustomMultipartResolver 类的 自定义文件上传处理类
     *
     * @return
     */
    @Bean(name = "multipartResolver")
    public MultipartResolver multipartResolver() {
        return new FileCommonsMultipartResolver();
    }
     //添加跨域,如果是前后端分类。
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "DELETE", "PUT")
                .maxAge(3600);

    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 注意如果filePath是写死在这里，一定不要忘记尾部的/或者\\，这样才能读取其目录下的文件
        registry.addResourceHandler("/**").addResourceLocations(
                "classpath:/META-INF/resources/",
                "classpath:/resources/",
                "classpath:/static/",
                "classpath:/public/",
                "classpath:/webapp/");
        //在windows环境下的图片存放资源路径
        String finalWinPath = System.getProperty("user.dir")+winPath;
        String os = System.getProperty("os.name");
        if (os.toLowerCase().startsWith("win")) {  //windows系统
            //第一个方法设置访问路径前缀，第二个方法设置资源路径
            log.info("win的存储路径{}",winPath);
            registry.addResourceHandler("/images/**").
                    addResourceLocations("file:"+finalWinPath);
        }else{//linux系统
            log.info("linux的存储路径{}",linuxPath);
            //在Linux环境下的图片存放资源路径
            registry.addResourceHandler("/images/**").
                    addResourceLocations("file:"+linuxPath);
        }
    }
}
